package com.example.dps;


import java.io.File;

import org.json.JSONException;
import org.json.JSONObject;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import com.downpayment.dps.R;

public class MainActivity extends Activity {


	
	ActionBarHelper actionBarHelper;
	
	WebHelper webHelper;
	
	DBHelper dbHelper;
	
	
	/*******************************************************/
	/** Buttons in the Main Menu
	/*******************************************************/
	ImageButton setGoalButton;
	
	ImageButton addMoneyButton;
	
	ImageButton viewSavingsButton;
	
	ImageButton mortgageCalcButton;
	
	ImageButton resourcesButton;
	
	ImageButton setupAccountButton;
	/******************************************************/
	
	
	
	
	
	/** set to 1 if its the first time using this app **/
	int setIntro = 1;
	
	@Override
	public void onBackPressed() {
		
		Intent intent = new Intent(this, SplashActivity.class);
		intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP);
		this.startActivity(intent);
	   finish();
	}


	@Override
	public void onConfigurationChanged(Configuration newConfig){
		super.onConfigurationChanged(newConfig);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.settings_menu, menu);
	    
	    if(this.webHelper.isLoggedIn()){
	    	menu.findItem(R.id.logout).setVisible(true);
	    	menu.findItem(R.id.login).setVisible(false);
	    }
	    else{
	    	menu.findItem(R.id.logout).setVisible(false);
	    	menu.findItem(R.id.login).setVisible(true);
	    }
	    
	    
	    return true;
	}
	
	//called after a login thread is executed
	public void onAuthenticate(String username, boolean result){

		
		if(result == true){
			this.dbHelper.setUsername(username);
			
			this.webHelper.getUserInfo();
			
			if(this.dbHelper.getMode() == DBHelper.CREATE_ACCOUNT_MODE)
				this.webHelper.getAccountInfo(false);

		}
		else{
			this.webHelper.logout();
		}

	}
	
	
	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = null;
		LayoutInflater inflater = null;
		
		switch (id) {
		case Constants.LOGIN_DIALOG:
			builder = new AlertDialog.Builder(this);
		    // Get the layout inflater
		    inflater = this.getLayoutInflater();

		    // Inflate and set the layout for the dialog
		    // Pass null as the parent view because its going in the dialog layout
		    builder.setView(inflater.inflate(R.layout.login_layout, null))
		    // Add action buttons
		           .setPositiveButton("Login", new DialogInterface.OnClickListener() {
		               @Override
		               public void onClick(DialogInterface dialog, int id) {
		            	   
		            	   EditText usernameText = (EditText)((AlertDialog)dialog).findViewById(R.id.loginUsernameValue);
		            	   EditText passwordText = (EditText)((AlertDialog)dialog).findViewById(R.id.loginPasswordValue);
		            	   CheckBox rememberMeBox = (CheckBox)((AlertDialog)dialog).findViewById(R.id.rememberMeCheckBox);
		            	   
		            	   boolean rememberMe = false;
		            	   if(rememberMeBox != null && rememberMeBox.isChecked()) rememberMe = true;
		            	   
		            	   if(rememberMe){
		            		   
		            	   }
		            	   
		            	   if(usernameText != null && passwordText != null){
		            		   String username = usernameText.getText().toString();
		            		   String password = passwordText.getText().toString();
		            		   
		            		   //Log.e("atasdf", username + password);
		            		   
		            		   MainActivity.this.webHelper.login(username,password, rememberMe);
		            	   }
		            	   else{
		            		   Toast.makeText(MainActivity.this, "Please enter your username and password", Toast.LENGTH_LONG).show();
		            	   }
		            	   //dialog.
		            	   
		               }
		           })
		           .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		               public void onClick(DialogInterface dialog, int id) {
		                   //LoginDialogFragment.this.getDialog().cancel();
		               }
		           });   
		    
		    /** set checked if remember me = true **/
		    AlertDialog dialog = (AlertDialog) builder.create();
		    
		    dialog.show();

		    TableRow forgotPass = (TableRow) dialog.findViewById(R.id.forgotPassword);
		    forgotPass.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {
					
					Log.e("CLICKED", "CLICKED FORGOT PASSWORD");
					Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.downpaymentsaver.com/downpaymentserver/forgotPassword.php"));
					startActivity(myIntent);
					
				}
		    	
		    });
		    return dialog;
		    
		}
		
		return null;
	}
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.settings:
	            
	        	/** go to settings activity **/
	        	Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
	        	this.startActivity(intent);
	            return true;
	            
	        case R.id.logout:
	        	/** log out user **/
	        	this.webHelper.logout();
	        	
	    		Intent i = new Intent();

	    		i.setClass(this, MainActivity.class);

	    		i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

	    		startActivity(i);
	        	
	            return true;
	            
	        case R.id.login:

	        	showDialog(Constants.LOGIN_DIALOG);
	        	
	        	return true;
	        	
	        default:
	            return super.onOptionsItemSelected(item);
	            
	    }
     
	            
	}
	
	/**
	 * Called when the Application is started
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.webHelper = new WebHelper(this);

		

		/** TODO **/
		/** load account and first time information on start up **/
		dbHelper = new DBHelper(this);
		
		
		/**
		 * NOTE: splash activity always sets first time = 0;
		 */
		if(dbHelper.getBoolean(dbHelper.COLUMN_FIRST_TIME)){
			setIntro = 1;
		}
		else setIntro = 0;
		
		
		/** if its the first time, display intro menu **/
		if(setIntro == 1){
			
			this.dbHelper.setBoolean(dbHelper.COLUMN_FIRST_TIME, 0);
			
			setContentView(R.layout.intro_layout);
			initIntroMenu();

			
		}
		else{
			setContentView(R.layout.activity_main);
			
			initMainMenu();

		}
		

	}
	
	public void initIntroMenu(){

		LinearLayout backgroundLayout = (LinearLayout) findViewById(R.id.backgroundLayout);
		
		backgroundLayout.setBackgroundDrawable(Utility.returnAdjustedBackgroundDrawable(this));
		
		/** add click listeners to Buttons **/
		addClickListeners();
		
		
	}
		
	
		

	
	public void initMainMenu(){
		
		LinearLayout backgroundLayout = (LinearLayout) findViewById(R.id.backgroundLayout);
		
		backgroundLayout.setBackgroundDrawable(Utility.returnAdjustedBackgroundDrawable(this));

		/** add click listeners to Buttons **/
		addClickListeners();
		
		
		/** Adjust button sizes to fit screen? **/
		adjustBackground();
		
		
	}
	
	
	

 
	
	/**
	 * adds functionality to the buttons. Defines behavior when buttons are clicked
	 */
	@SuppressLint("NewApi")
	public void addClickListeners(){
		
		TextView aboutText = (TextView) findViewById(R.id.aboutText);
		
		aboutText.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				
				Intent intent = new Intent(MainActivity.this, AboutThisAppActivity.class);
				startActivity(intent);
			}
			
		});
		
		TextView privacyPolicyText = (TextView) findViewById(R.id.privacyPolicyText);
		
		privacyPolicyText.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				
				Intent intent = new Intent(MainActivity.this, PrivacyPolicyActivity.class);
				startActivity(intent);
			}
			
		});

		if(setIntro == 1){
			initIntroButtonListeners();
		}
		else{
			initMainButtonListeners();
		}
		
		
		
	
	}
	
	private void initIntroButtonListeners() {
		ImageButton continueButton = (ImageButton) findViewById(R.id.continueButton);
		
		continueButton.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				
				/** update set intro to false **/
				disableIntro();
				
				/** set content view to main **/
				MainActivity.this.setContentView(R.layout.activity_main);
				
				LinearLayout backgroundLayout = (LinearLayout) findViewById(R.id.backgroundLayout);
				
				backgroundLayout.setBackgroundDrawable(Utility.returnAdjustedBackgroundDrawable(MainActivity.this));
				
				initMainButtonListeners();
				
				
			}
			
			
		});
		
		continueButton.setOnTouchListener(new OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				ImageButton view = (ImageButton) v;
				
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					view.setImageDrawable(view.getResources().getDrawable(R.drawable.lets_get_started_btn_clicked));
				}
				else if(event.getAction() == MotionEvent.ACTION_UP){
					
					view.setImageDrawable(view.getResources().getDrawable(R.drawable.lets_get_started_btn));
					
				}
				else if(event.getAction() == MotionEvent.ACTION_CANCEL){
					view.setImageDrawable(view.getResources().getDrawable(R.drawable.lets_get_started_btn));
				}
				return false;
			}
			
		});
		
	}

	protected void disableIntro() {
		
		this.setIntro = 0;
		
		/**update database with this information **/
		
	}

	public void initMainButtonListeners(){
		/*******************************************************/
		/** Buttons in the Main Menu
		/*******************************************************/
		setGoalButton = (ImageButton) findViewById(R.id.setGoalButton);
		
		addMoneyButton = (ImageButton) findViewById(R.id.addMoneyButton);
		
		viewSavingsButton = (ImageButton) findViewById(R.id.viewSavingsButton);
		
		mortgageCalcButton = (ImageButton) findViewById(R.id.mortgageCalcButton) ;
		
		resourcesButton = (ImageButton) findViewById(R.id.resourcesButton);
		
		setupAccountButton = (ImageButton) findViewById(R.id.setupAccountButton);
		/******************************************************/
		
		
		
		
		/** When set goal button is clicked, go to Set Goal Activity **/
		setGoalButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View view) {
				/** opens tabbed view starting on set savings goal **/
				
				Intent intent = new Intent(MainActivity.this, TabRoot.class);
				intent.putExtra("START_TAB", "set_savings_goal");
				MainActivity.this.startActivity(intent);
				
			}	
		});
		setGoalButton.setOnTouchListener(new OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				/** get the root element of the button view **/
		    	ImageView view = (ImageView) v;
		    	
		        if(event.getAction() == MotionEvent.ACTION_DOWN) {
		        	/** change the image button picture when clicked **/
		        	view.setImageDrawable(v.getResources().getDrawable(R.drawable.create_savings_menu_btn_clicked));
		        } else if (event.getAction() == MotionEvent.ACTION_UP) {
		        	view.setImageDrawable(v.getResources().getDrawable(R.drawable.create_savings_menu_btn));
		        }
		        else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
		        	view.setImageDrawable(v.getResources().getDrawable(R.drawable.create_savings_menu_btn));
		        }
				return false;
			}
		});

		

		/** when add money is clicked, jump to add money activity **/
		addMoneyButton.setOnClickListener(new OnClickListener(){
			public void onClick(View view){
				/** opens tabbed view starting on add money **/
				Intent intent = new Intent(MainActivity.this, TabRoot.class);
				intent.putExtra("START_TAB", "add_money");
				MainActivity.this.startActivity(intent);
			}
		});
		addMoneyButton.setOnTouchListener(new OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				/** get the root element of the button view **/
				ImageView view = (ImageView) v;
		    	
		        if(event.getAction() == MotionEvent.ACTION_DOWN) {
		        	/** change the image button picture when clicked **/
		        	view.setImageDrawable(v.getResources().getDrawable(R.drawable.add_money_menu_btn_clicked));
		        } else if (event.getAction() == MotionEvent.ACTION_UP) {
		        	view.setImageDrawable(v.getResources().getDrawable(R.drawable.add_money_menu_btn));
		        }
		        else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
		        	view.setImageDrawable(v.getResources().getDrawable(R.drawable.add_money_menu_btn));
		        }
				return false;
			}
		});
		
		
		
		
		/** when view savings is clicked, jump to view savings activity **/
		viewSavingsButton.setOnClickListener(new OnClickListener(){
			public void onClick(View view){
				
				/** opens tabbed view starting on view savings **/
				Intent intent = new Intent(MainActivity.this, TabRoot.class);
				intent.putExtra("START_TAB", "view_savings");
				MainActivity.this.startActivity(intent);
			}
		});
		viewSavingsButton.setOnTouchListener(new OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				/** get the root element of the button view **/
		    	ImageView view = (ImageView) v;
		    	
		        if(event.getAction() == MotionEvent.ACTION_DOWN) {
		        	/** change the image button picture when clicked **/
		        	view.setImageDrawable(v.getResources().getDrawable(R.drawable.view_savings_menu_btn_clicked));
		        } else if (event.getAction() == MotionEvent.ACTION_UP) {
		        	view.setImageDrawable(v.getResources().getDrawable(R.drawable.view_savings_menu_btn));
		        }
		        else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
		        	view.setImageDrawable(v.getResources().getDrawable(R.drawable.view_savings_menu_btn));
		        }
				return false;
			}
		});
		
		
		/** when mortgage calculator button is pressed, jump to mortgage calculator activity **/
		mortgageCalcButton.setOnClickListener(new OnClickListener(){
			public void onClick(View view){
				/** opens tabbed view starting on mortgage calc tab **/
				Intent intent = new Intent(MainActivity.this, TabRoot.class);
				intent.putExtra("START_TAB", "mortgage_calc");
				MainActivity.this.startActivity(intent);
			}
		});
		mortgageCalcButton.setOnTouchListener(new OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				/** get the root element of the button view **/
		    	ImageView view = (ImageView) v;
		    	
		        if(event.getAction() == MotionEvent.ACTION_DOWN) {
		        	/** change the image button picture when clicked **/
		        	view.setImageDrawable(v.getResources().getDrawable(R.drawable.calculators_menu_btn_clicked));
		        } else if (event.getAction() == MotionEvent.ACTION_UP) {
		        	view.setImageDrawable(v.getResources().getDrawable(R.drawable.calculators_menu_btn));
		        }
		        else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
		        	view.setImageDrawable(v.getResources().getDrawable(R.drawable.calculators_menu_btn));
		        }
				return false;
			}
		});
		
		
		
		
		/** When resources button is clicked, jump to resources activity **/
		resourcesButton.setOnClickListener(new OnClickListener(){
			public void onClick(View view){
				/** TODO opens tabbed view starting on mortgage calculator **/
					Intent intent = new Intent(MainActivity.this, TabRoot.class);
					intent.putExtra("START_TAB", "resources");
					MainActivity.this.startActivity(intent);
			}
		});
		resourcesButton.setOnTouchListener(new OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				/** get the root element of the button view **/
		    	ImageView view = (ImageView) v;
		    	
		        if(event.getAction() == MotionEvent.ACTION_DOWN) {
		        	/** change the image button picture when clicked **/
		        	view.setImageDrawable(v.getResources().getDrawable(R.drawable.buying_facts_menu_btn_clicked));
		        } else if (event.getAction() == MotionEvent.ACTION_UP) {
		        	view.setImageDrawable(v.getResources().getDrawable(R.drawable.buying_facts_menu_btn));
		        }
		        else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
		        	view.setImageDrawable(v.getResources().getDrawable(R.drawable.buying_facts_menu_btn));
		        }
				return false;
			}
		});
		
		
		
		
		
		
	}
	
	
	public void adjustBackground(){
		
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		int height = displaymetrics.heightPixels;
		int width = displaymetrics.widthPixels;
		
		int screenWidth = 0;
		
		Drawable unscaled = getResources().getDrawable(R.drawable.content_bk_slice);
		
		Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.content_bk_slice);
		
		bitmap = Bitmap.createScaledBitmap(bitmap, width, bitmap.getHeight(), false);
		
		BitmapDrawable scaled = new BitmapDrawable(getResources(), bitmap);
		
		scaled.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
		
		LinearLayout backgroundLayout = (LinearLayout) findViewById(R.id.backgroundLayout);
		
		backgroundLayout.setBackgroundDrawable(scaled);
		
	}
	
	
	public void onGetUserInfo(JSONObject json) {
		// TODO Auto-generated method stub

		try {
			String username = json.getString("username");
			String email = json.getString("email");
			String password = json.getString("password");
			int mode = json.getInt("mode");
			int achConfirmed = json.getInt("achConfirmed");
			
			
			//Log.ee("ongetUserInfo View Savings", "mode = " + mode);
			
			this.dbHelper.setColumnString(DBHelper.COLUMN_USERNAME, username);
			this.dbHelper.setColumnString(DBHelper.COLUMN_EMAIL, email);
			this.dbHelper.setColumnString(DBHelper.COLUMN_PASSWORD, password);
			
			this.dbHelper.setMode(mode);
			this.dbHelper.setBoolean(DBHelper.COLUMN_ACH_CONFIRMED, achConfirmed);
			
			
			
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	
	

}
